<?php

namespace App\Http\Middleware;

use App\Models\Admin;
use App\Models\AdminToken;
use App\Models\Role;
use Closure;

class UserMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->header('Authorization')){
            return Error('无权访问！', 401);
        }else{
            //验证token过期时间
            $token = $request->header('Authorization');

            $userToken = AdminToken::where('token',$token)
                ->where('expire_time','>',date('Y-m-d H:i:s',time()))
                ->first();

            if (!$userToken){
                return Error('令牌已过期，请重新登录！', 401);
            }

            //验证账户是否可用
            $user = Admin::find($userToken->user_id);
            if (!$user->status){
                return Error('账户已禁用，请联系管理员！', 401);
            }

            //验证角色是否可用
            $role = Role::find($user->role_id);
            if (!$role->status){
                return Error('角色《'.$role->role_name.'》已禁用，请联系管理员！', 401);
            }

            if ($user){
                $request->attributes->set('currentUserId',$userToken->user_id);
                return $next($request);
            }else{
                return Error('用户不存在或令牌已过期，请重新登录！', 401);
            }
        }
    }
}
